package com.heima.user.controller.v1;

import com.alibaba.fastjson.JSON;
import com.heima.apis.user.ApUserLoginControllerApi;
import com.heima.common.aliyun.util.AliSendSms;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.user.service.ApUserLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/v1/login")
public class ApUserLoginController implements ApUserLoginControllerApi {

    @Autowired
    ApUserLoginService apUserLoginService;

    @Autowired
    KafkaTemplate kafkaTemplate;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * app端登录
     *
     * @param dto
     * @return
     */
    @Override
    @PostMapping("/login_auth")
    public ResponseResult login(@RequestBody LoginDto dto) {
        return apUserLoginService.login(dto);
    }

    /**
     * 发送验证码
     *
     * @param dto
     * @return
     */
    @Override
    @PostMapping("/sendCodeToPhone")
    public ResponseResult sendCodeToPhone(@RequestBody LoginDto dto) {
        String telephone=dto.getPhone();
        String code= AliSendSms.generateValidateCode(6);
        System.out.println("验证码为" + code);
        Map<String, String> map=new HashMap();
        map.put("telephone",telephone);
        map.put("code",code);
        //转发给kafka发短信
//        kafkaTemplate.send("sendSms-topic", JSON.toJSONString(map));
        //存入redis
        redisTemplate.opsForValue().set("001"+telephone,code,90, TimeUnit.SECONDS);
//        System.out.println("缓存中"+redisTemplate.opsForValue().get("001" + telephone));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
